package com.sssoft.Yundian.activity;

import java.util.ArrayList;
import java.util.List;

import com.readystatesoftware.viewbadger.BadgeView;
import com.sssoft.Yundian.R;
import com.sssoft.Yundian.Dao.GoodsDao;
import com.sssoft.Yundian.Dao.PordersDao;
import com.sssoft.Yundian.bean.Goods;
import com.sssoft.Yundian.bean.Porders;
import com.sssoft.Yundian.view.CustomViewPager;
import com.sssoft.Yundian.view.slidingMenu;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 主界面
 * 
 * @author Jiang 2017.10.11
 *
 */
@SuppressLint("InflateParams")
public class MainActivity extends Activity implements View.OnClickListener {
	private slidingMenu mLeftMenu;
	private List<Goods> goods;
	private GoodsDao gdao;
	private PordersDao pordersdao;

	private TextView tv_title;
	private LinearLayout ll_dots;
	private Button bt_buy;
	private TextView tv_total;
	private ImageView iv_buy;
	private RelativeLayout rl_manager;
	private RelativeLayout rl_account;
	private RelativeLayout rl_card;
	private RelativeLayout rl_vipcard;
	private RelativeLayout rl_recharge;

	private View target2;
	private BadgeView badge2;
	private View getlistview;
	private Builder builder;
	private AlertDialog dialog;

	private MyAdapter mAdapter;
	private CustomViewPager pv_goods;
	private CardAdapter adapter;
	private ListView listview;

	private List<ImageView> dots = new ArrayList<ImageView>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		initView();

	}

	public void initView() {
		mLeftMenu = (slidingMenu) findViewById(R.id.id_menu);
		tv_title = (TextView) findViewById(R.id.tv_title);
		ll_dots = (LinearLayout) findViewById(R.id.ll_dots);
		bt_buy = (Button) findViewById(R.id.bt_buy);
		tv_total = (TextView) findViewById(R.id.tv_total);
		iv_buy = (ImageView) findViewById(R.id.iv_buy);
		rl_manager = (RelativeLayout) findViewById(R.id.rl_manage);
		rl_account = (RelativeLayout) findViewById(R.id.rl_account);
		rl_card = (RelativeLayout) findViewById(R.id.rl_card);
		rl_vipcard = (RelativeLayout) findViewById(R.id.rl_vipcard);
		rl_recharge = (RelativeLayout) findViewById(R.id.rl_recharge);
		
		//左侧菜单点击事件
        MyListener ml=new MyListener();
		rl_manager.setOnClickListener(ml);
		rl_account.setOnClickListener(ml);
		rl_card.setOnClickListener(ml);
		rl_vipcard.setOnClickListener(ml);
		rl_recharge.setOnClickListener(ml);


		target2 = findViewById(R.id.iv_buy);
		badge2 = new BadgeView(MainActivity.this, target2);
		pordersdao = new PordersDao(MainActivity.this);

		// 商品显示区域
		create_viewpager();

		// 选好跳转
		bt_buy.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				long mark_id = pordersdao.insetInPorders(goods);
				Toast.makeText(MainActivity.this, mark_id + "", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(MainActivity.this, ConsumptionActivity.class);
				intent.putExtra("orders_id", mark_id);
				startActivity(intent);
			}
		});

		// 查看购物车
		iv_buy.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CreateDialog();
			}
		});

//		mLeftMenu.setOnTouchListener(new OnTouchListener() {
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				// 侧面菜单取消滑动只能点击
//				return true;
//			}
//		});

	}

	public void create_viewpager() {
		gdao = new GoodsDao(MainActivity.this);
		goods = gdao.queryAll();
		pv_goods = (CustomViewPager) findViewById(R.id.vp_goods);
		mAdapter = new MyAdapter(this, goods, this);
		pv_goods.setAdapter(mAdapter);
		if (goods.size() > 8) {
			initDot();
		}
		pv_goods.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				for (int i = 0; i < dots.size(); i++) {
					if (i == position) {
						dots.get(i).setBackgroundResource(R.drawable.dot_green);
					} else {
						dots.get(i).setBackgroundResource(R.drawable.dot_gray);
					}
				}
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
	}
	
	
	//左侧菜单点击事件
	class MyListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.rl_manage:
				Toast.makeText(MainActivity.this, "gg", Toast.LENGTH_SHORT).show();
				break;
			case R.id.rl_account:
				Toast.makeText(MainActivity.this, "gg", Toast.LENGTH_SHORT).show();
				break;
			case R.id.rl_card:
				Toast.makeText(MainActivity.this, "gg", Toast.LENGTH_SHORT).show();
				break;
			case R.id.rl_vipcard:
				Toast.makeText(MainActivity.this, "gg", Toast.LENGTH_SHORT).show();
				break;
			case R.id.rl_recharge:
				Toast.makeText(MainActivity.this, "gg", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;

			}

		}
	}

	public void toggleMenu(View v) {
		mLeftMenu.toggle();
	}

	/**
	 * 绘制导航点
	 */
	private void initDot() {
		for (int i = 0; i < (goods.size() / 9 + 1); i++) {
			ImageView imageView = new ImageView(this);
			// 创建一个ImageView来放置圆点，并确定ImageView的宽高
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
			params.leftMargin = 10;
			params.rightMargin = 10;
			params.topMargin = 5;
			params.bottomMargin = 5;
			imageView.setLayoutParams(params);
			dots.add(imageView);
			// 由于刚进去引导页时出现的是第一个引导页，故此时的导航点设置为红色
			if (i == 0) {
				dots.get(i).setBackgroundResource(R.drawable.dot_green);
			} else {
				dots.get(i).setBackgroundResource(R.drawable.dot_gray);
			}
			ll_dots.addView(imageView);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.

		return super.onOptionsItemSelected(item);
	}

	private void ishaskey(Goods good) {
		if (good.isSelected()) {
			good.setSelectedNum(good.getSelectedNum() + 1);
		} else {
			good.setSelected(true);
			good.setSelectedNum(1);
		}
		mAdapter.refresh(goods);
		total();
	}

	private void total() {
		float sum = 0;
		int total = 0;
		for (int i = 0; i < goods.size(); i++) {
			if (goods.get(i).isSelected()) {
				sum = sum + Float.parseFloat(goods.get(i).getGoods_price()) * goods.get(i).getSelectedNum();
				total = total + goods.get(i).getSelectedNum();
			}
		}

		tv_total.setText(sum + "");
		badge2.setText(total + "");
		badge2.show();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int pageNum = pv_goods.getCurrentItem();
		switch (v.getId()) {
		case R.id.ll_item1:
			ishaskey(goods.get(pageNum * 9 + 0));
			break;
		case R.id.ll_item2:
			ishaskey(goods.get(pageNum * 9 + 1));
			break;
		case R.id.ll_item3:
			ishaskey(goods.get(pageNum * 9 + 2));
			break;
		case R.id.ll_item4:
			ishaskey(goods.get(pageNum * 9 + 3));
			break;
		case R.id.ll_item5:
			ishaskey(goods.get(pageNum * 9 + 4));
			break;
		case R.id.ll_item6:
			ishaskey(goods.get(pageNum * 9 + 5));
			break;
		case R.id.ll_item7:
			ishaskey(goods.get(pageNum * 9 + 6));
			break;
		case R.id.ll_item8:
			ishaskey(goods.get(pageNum * 9 + 7));
			break;
		case R.id.ll_item9:
			ishaskey(goods.get(pageNum * 9 + 8));
			break;
		default:
			break;
		}
	}

	public void CreateDialog() {

		// 动态加载一个listview的布局文件进来
		LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
		getlistview = inflater.inflate(R.layout.shopping_card, null);

		// 给ListView绑定内容
		listview = (ListView) getlistview.findViewById(R.id.lv_shopping_goods);
		adapter = new CardAdapter();
		// 给listview加入适配器
		listview.setAdapter(adapter);
		listview.setItemsCanFocus(false);

		builder = new AlertDialog.Builder(this);
		builder.setIcon(R.drawable.ic_launcher);
		// 设置加载的listview
		builder.setView(getlistview);

		dialog = builder.create();
		Window window = dialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		window.setGravity(Gravity.BOTTOM);
		// lp.x = 100; // 新位置X坐标
		lp.y = 130; // 新位置Y坐标
		// // lp.width = 300; // 宽度
		// // lp.height = 300; // 高度
		// lp.alpha = 1f; // 透明度
		window.setAttributes(lp);
		// WindowManager m = getWindowManager();
		// Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
		dialog.show();

		ImageView iv_clear = (ImageView) getlistview.findViewById(R.id.iv_clear);
		iv_clear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				android.content.DialogInterface.OnClickListener listener = new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog2, int which) {
						for (int i = 0; i < goods.size(); i++) {
							goods.get(i).setSelected(false);
							goods.get(i).setSelectedNum(0);
						}
						dialog.hide();
						// listview.setAdapter(adapter);
						mAdapter.refresh(goods);
						total();

					}
				};

				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("确定全部清空？");
				builder.setPositiveButton("确定", listener);
				builder.setNegativeButton("取消", null);
				builder.show();

			}

		});
	}

	class CardAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			int size = 0;
			for (int i = 0; i < goods.size(); i++) {
				if (goods.get(i).isSelected()) {
					size++;
				}
			}
			return size;
		}

		@Override
		public Object getItem(int position) {
			int size = 0;
			Goods a = null;
			for (int i = 0; i < goods.size(); i++) {
				if (goods.get(i).isSelected()) {
					if (size == position) {
						a = goods.get(i);
					}
					size++;
				}
			}
			return a;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View item = convertView != null ? convertView
					: View.inflate(getApplicationContext(), R.layout.show_shopping, null);

			TextView tv_shop_name = (TextView) item.findViewById(R.id.tv_shop_name);
			TextView tv_shop_price = (TextView) item.findViewById(R.id.tv_shop_price);
			TextView tv_shop_num = (TextView) item.findViewById(R.id.tv_shop_num);
			ImageView ib_shop_down = (ImageView) item.findViewById(R.id.ib_shop_down);
			ImageView ib_shop_up = (ImageView) item.findViewById(R.id.ib_shop_up);

			int num = 0;
			Goods b = null;
			for (int i = 0; i < goods.size(); i++) {
				if (goods.get(i).isSelected()) {
					if (num == position) {
						b = goods.get(i);
					}
					num++;
				}
			}
			final Goods a = b;

			tv_shop_name.setText(a.getGoods_name());
			tv_shop_price.setText(a.getGoods_price());
			tv_shop_num.setText(a.getSelectedNum() + "");

			ib_shop_up.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					a.setSelectedNum(a.getSelectedNum() + 1);
					notifyDataSetChanged();
					mAdapter.refresh(goods);
					total();
				}
			});

			ib_shop_down.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					a.setSelectedNum(a.getSelectedNum() - 1);
					if (a.getSelectedNum() == 0) {
						a.setSelected(false);
					}
					notifyDataSetChanged();
					mAdapter.refresh(goods);
					total();
				}
			});
			return item;
		}
	}
}
